<?php
/*
 * Author  : top-songshijie
 * Email   : 997031758@qq.com
 * DateTime: 2023/02/22 14:35
 */

namespace SSJ\LaravelHelper\Support;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Illuminate\Support\Facades\Validator;
use SSJ\LaravelHelper\Exceptions\UnprocessableEntityException;

class Util
{
    /**
     * 验证
     *
     * @param array $param
     * @param array $rules
     * @param array $messages
     * @param array $customAttributes
     *
     * @throws UnprocessableEntityException
     */
    public static function validate(array $param, array $rules, array $messages = [], array $customAttributes = [])
    {
        $validator = Validator::make($param, $rules, $messages, $customAttributes);

        if ($validator->fails()) {
            throw new UnprocessableEntityException($validator->errors()->first());
        }
    }

    /**
     * request 请求
     *
     * @param string $u
     * @param array  $p
     * @param string $m
     *
     * @return mixed
     */
    public static function request($u, $p, $m = 'POST')
    {
        $client = new Client();

        if ($m == 'POST') {
            $response = $client->request($m, $u, ['json' => $p]);
        } else {
            $response = $client->request($m, $u . '?' . http_build_query($p));
        }

        return json_decode($response->getBody(), true);
    }

    /**
     * 拆分为开始与结束的数组格式时间
     *
     * @param string $time
     * @param string $delimiter
     *
     * @return array
     * @throws UnprocessableEntityException
     */
    public static function splitTime($time, $delimiter = '\r\n')
    {
        $tmp = explode($delimiter, $time);
        if (count($tmp) !== 2) {
            throw new UnprocessableEntityException('time 格式不正确');
        }

        return [$tmp[0], $tmp[1]];
    }

    /**
     * 构建真实的sql语句
     *
     * @param $builder
     *
     * @return string
     */
    public static function sql($builder)
    {
        return vsprintf(str_replace("?", "'%s'", $builder->toSql()), $builder->getBindings());
    }

    /**
     * 读取excel文件内容
     *
     * @param string $file_path 文件路径
     * @param array  $template  例：['A' => ['field' => 'name', 'remark' => '姓名']]
     *
     * @return array
     * @throws UnprocessableEntityException
     */
    public static function readExcel($file_path, $template)
    {
        $spreadsheet = IOFactory::load($file_path);
        $body        = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        $header      = array_shift($body);

        /* 验证header信息 */
        foreach ($template as $k => $item) {
            if (!isset($header[$k]) or $header[$k] != $item['remark']) {
                throw new UnprocessableEntityException(sprintf("模板头字段【%s】校验失败", $item['remark']));
            }
        }

        /* 获取需要的数据格式 */
        $list = [];
        foreach ($body as $k => $item) {
            $tmp = [];
            foreach ($template as $k2 => $item2) {
                //验证必填字段
                if (Str::startsWith($item2['remark'], '*') && !$item[$k2]) {
                    throw new UnprocessableEntityException(sprintf("第【%s】行的属性【%s】不能为空", $k + 2, $item2['remark']));
                }
                $tmp = array_merge($tmp, [$item2['field'] => trim($item[$k2])]);
            }
            array_push($list, $tmp);
        }

        return [$header, $body, $list];
    }
}
